package com.sunday.haowushop.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.Constants;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.StringUtils;
import com.sunday.common.utils.TimeCount;
import com.sunday.common.utils.ToastUtils;
import com.sunday.common.widgets.ClearEditText;
import com.sunday.haowushop.R;
import com.sunday.haowushop.common.BaseApp;
import com.sunday.haowushop.entity.Member;
import com.sunday.haowushop.http.ApiClient;
import com.sunday.haowushop.ui.MainActivity;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2017/4/18.
 */

public class LoginActivity extends BaseActivity {
    @Bind(R.id.et_phone)
    ClearEditText etPhone;
    @Bind(R.id.et_code)
    ClearEditText etCode;
    @Bind(R.id.send_code)
    TextView sendCode;
    @Bind(R.id.btn_login)
    TextView btnLogin;
    @Bind(R.id.btn_wechat_login)
    RelativeLayout btnWechatLogin;

    private UMShareAPI umShareAPI;
    private TimeCount timeCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        umShareAPI = UMShareAPI.get(this);
        umShareAPI.deleteOauth(LoginActivity.this, SHARE_MEDIA.WEIXIN, null);
        timeCount=new TimeCount(60000,1000,sendCode);
        final InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(etPhone.getWindowToken(), 0);
    }

    @OnClick({R.id.btn_login, R.id.btn_wechat_login,R.id.send_code})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.send_code:
                String mobile=etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile)|| !StringUtils.isMobileNO(mobile)){
                    ToastUtils.showToast(mContext,"请输入正确的手机号");
                    return;
                }
                sendCode(mobile);
                break;
            case R.id.btn_login:
                String mobile1=etPhone.getText().toString().trim();
                if (TextUtils.isEmpty(mobile1)|| !StringUtils.isMobileNO(mobile1)){
                    ToastUtils.showToast(mContext,"请输入正确的手机号");
                    return;
                }
                String code=etCode.getText().toString().trim();
                if (TextUtils.isEmpty(code)){
                    ToastUtils.showToast(mContext,"请输入验证码");
                    return;
                }
                login(mobile1,code);

                break;
            case R.id.btn_wechat_login:
                umShareAPI.getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthInfoListener);
                break;
        }
    }


    private void sendCode(String mobile){
        Call<ResultDO> call= ApiClient.getApiAdapter().sendCode(mobile,2);
        call.enqueue(new Callback<ResultDO>() {
            @Override
            public void onResponse(Call<ResultDO> call, Response<ResultDO> response) {
                if (isFinish||response.body()==null){return;}
                if (response.body().getCode()==0){
                    ToastUtils.showToast(mContext,"验证码已发送到手机");
                    timeCount.start();
                }else {
                    ToastUtils.showToast(mContext,response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO> call, Throwable t) {
                ToastUtils.showToast(mContext, R.string.network_error);
            }
        });
    }

    private void login(String mobileNo,String code){
        Call<ResultDO<Member>> call1 = ApiClient.getApiAdapter().login(mobileNo,code);
        call1.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                dissMissDialog();
                ResultDO<Member> resultDO = response.body();
                if (resultDO==null||isFinish){
                    return;
                }
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult()==null){return;}
                    SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                    SharePerferenceUtils.getIns(mContext).putBoolean(Constants.IS_LOGIN,true);
                    BaseApp.getInstance().setMember(resultDO.getResult());
                    intent=new Intent(mContext, MainActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {
                dissMissDialog();
                ToastUtils.showToast(mContext, R.string.send_code_failed);
            }
        });
    }

    private String logo, nickName, unionid, openid;
    private UMAuthListener umAuthInfoListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
            switch (share_media) {
                case WEIXIN:
                    openid = map.get("openid");
                    logo = map.get("iconurl");
                    nickName = map.get("name");
                    unionid = map.get("unionid");
                    thirdLogin();
                    break;
            }
        }

        @Override
        public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
            ToastUtils.showToast(mContext, "授权失败");
        }

        @Override
        public void onCancel(SHARE_MEDIA share_media, int i) {
            ToastUtils.showToast(mContext, "授权取消");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);

    }

    private void thirdLogin() {
        Call<ResultDO<Member>> call = ApiClient.getApiAdapter().wxLogin(nickName, logo, unionid, openid);
        call.enqueue(new Callback<ResultDO<Member>>() {
            @Override
            public void onResponse(Call<ResultDO<Member>> call, Response<ResultDO<Member>> response) {
                ResultDO<Member> resultDO = response.body();
                if (resultDO == null) {
                    return;
                }
                if (resultDO.getCode() == 0) {
                    if (resultDO.getResult() == null || isFinish) {
                        return;
                    }
                    if (TextUtils.isEmpty(resultDO.getResult().getMobile())) {
                        //绑定手机号
                        intent = new Intent(mContext, MobileLoginActivity.class);
                        intent.putExtra("type", 1);
                        intent.putExtra("memberId", resultDO.getResult().getId());
                        startActivity(intent);
                    } else if (resultDO.getResult().getMemberLevel() >= 3) {
                        SharePerferenceUtils.getIns(mContext).saveOAuth(resultDO.getResult());
                        SharePerferenceUtils.getIns(mContext).putBoolean(Constants.IS_LOGIN, true);
                        BaseApp.getInstance().setMember(resultDO.getResult());
                        intent = new Intent(mContext, MainActivity.class);
                        startActivity(intent);
                    }

                } else {
                    ToastUtils.showToast(mContext, resultDO.getMessage());
                }
            }

            @Override
            public void onFailure(Call<ResultDO<Member>> call, Throwable t) {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        if (timeCount!=null){
            timeCount.cancel();
        }
    }
}
